package com.kwok.rbac.application.advice;

import com.kwok.rbac.application.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对controller层接口返回结果进行统一包装处理
 */
//ResponseBodyAdvice<Object>这里的泛型指的是Controller返回值
@ControllerAdvice
@Slf4j
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //这里返回true后才会继续执行下面的beforeBodyWrite方法
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.debug("Controller接口返回的内容:{}",body);
        //如果Controller中的method没有返回值，则返回空
        if(body == null){
            return null;
        }
        //Controller接口返回的内容body已经用R进行了包装
        if (body instanceof R){
            return body;
        }
        //重新用R包装Controller接口返回的内容body
        return R.success(body);
    }
}
